package com.lagou.client;

import com.lagou.handler.UserClientHandler;
import com.lagou.handler.UserClientHandler2;
import com.lagou.pojo.JSONSerializer;
import com.lagou.pojo.RpcDecoder;
import com.lagou.pojo.RpcEncoder;
import com.lagou.pojo.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RPCConsumer {
    //创建线程池
    private static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static UserClientHandler userClientHandler;
    private static UserClientHandler2 userClientHandler2;

    public static void initClient() throws InterruptedException {
        userClientHandler = new UserClientHandler();
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new StringDecoder());

                        pipeline.addLast(userClientHandler);
                    }
                });

        bootstrap.connect("127.0.0.1",8999).sync();
    }

    public static void initClient2() throws InterruptedException {
        userClientHandler2 = new UserClientHandler2();
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new RpcEncoder(RpcRequest.class,new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());//success

                        pipeline.addLast(userClientHandler2);
                    }
                });

        bootstrap.connect("127.0.0.1",8999).sync();
    }

    public static Object crreateProxy(Class<?> serviceClass, final String providerParam){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                if (userClientHandler == null){
                    initClient();
                }

                userClientHandler.setParam(providerParam+objects[0]);

                Object result = executorService.submit(userClientHandler).get();


                return result;
            }
        });
    }

    public static Object crreateProxy2(Class<?> serviceClass){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                if (userClientHandler2 == null){
                    initClient2();
                }

                RpcRequest rpcRequest = new RpcRequest();
                rpcRequest.setClassName(serviceClass.getName());
                rpcRequest.setMethodName(method.getName());
                rpcRequest.setRequestId(UUID.randomUUID().toString());
                rpcRequest.setParameterTypes(getParameterTypes(objects));
                rpcRequest.setParameters(objects);

                userClientHandler2.setParam(rpcRequest);

                Object result = executorService.submit(userClientHandler2).get();


                return result;
            }
        });
    }

    private static Class<?>[] getParameterTypes(Object[] objects) {
        Class<?>[] classes = new Class[objects.length];
        for (int i = 0; i < objects.length; i++) {
            classes[i] = objects[i].getClass();
        }
        return classes;
    }
}
